package com.rinlink.spock.demo.service;

import com.rinlink.spock.demo.common.ErrorCodes;
import com.rinlink.spock.demo.repository.OrderRepository;
import com.rinlink.spock.demo.repository.model.OrderDO;
import com.rinlink.spock.demo.service.model.CreateOrderInDTO;
import lombok.Getter;

public class OrderService{

    @Getter
    private UserService userService;

    @Getter
    private GoodsService goodsService;

    @Getter
    private OrderRepository orderRepository;

    public void create(CreateOrderInDTO indto){
        if(!getUserService().exists(indto.getUserId())){
            throw new IllegalArgumentException(ErrorCodes.USER_NOT_EXISTS.name());
        }
        if(!getGoodsService().exists(indto.getGoodsId())){
            throw new IllegalArgumentException(ErrorCodes.GOODS_NOT_EXISTS.name());
        }
        int price = getGoodsService().getPrice(indto.getGoodsId());
        int balance = getUserService().getBalance(indto.getUserId());
        if(price > balance){
            throw new IllegalArgumentException(ErrorCodes.BALANCE_NOT_ENOUGH.name());
        }
        OrderDO orderDO = new OrderDO()
                .setGoodsId(indto.getGoodsId())
                .setUserId(indto.getUserId());
        getOrderRepository().insert(orderDO);
    }

}